import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/putaway/putawaydialogscreen.dart';
import 'package:opene/ui/putaway/putawaymodel.dart';
import 'package:opene/ui/returns/finalprocess/finalprocessrpsreen.dart';
import 'package:opene/ui/returns/finalprocess/finalprocesstrkscreen.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:toast/toast.dart';

class FinalProcessLpnScreen extends StatelessWidget {
  String batchNo;
  List<String> data;

  FinalProcessLpnScreen({this.batchNo, this.data});

  @override
  Widget build(BuildContext context) {
    return FinalProcessLpnScreenPage( batchNo: batchNo, data: data);
  }
}

class FinalProcessLpnScreenPage extends StatefulWidget {
  String batchNo;
  List<String> data;

  FinalProcessLpnScreenPage({ this.batchNo, this.data});

  @override
  _FinalProcessLpnPageState createState() => _FinalProcessLpnPageState( batchNo: batchNo, data: data);
}

class _FinalProcessLpnPageState extends BaseState<FinalProcessLpnScreen> {
  String batchNo;
  List<String> data;
  _FinalProcessLpnPageState({this.batchNo, this.data});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "FinalProcess:TRK#";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "BatchNo: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                Utils.getStringisEmpty(batchNo),
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      returnCheckTrackingCode(text);
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                            returnCheckTrackingCode(text);
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "scan tracking number",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
            ],
          ),
          Text(
            "pending Trk# List:",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(
            flex: 1,
            child: setListView(),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        String lpn = data[index];
        return Column(
          children: [
            GestureDetector(
              onTap: () {},
              child: Text(
                Utils.getStringisEmpty(lpn),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
              ),
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void returnCheckTrackingCode(String lpn) async {

    Map<String, dynamic> map = new HashMap();
    map["batchNo"] = batchNo;
    map["lpn"] = lpn;

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnCheckLpn, params: map);

    if (baseResponse.status == 200) {
      List<FinalProcessLpn> finalProcessLpns = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => FinalProcessLpn.fromJson(userJson)).toList());
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => FinalProcessTrkScreen(oldIbLpn: lpn, batchNo: batchNo, finalProcessLpns: finalProcessLpns)),
      ).then((value) {
        if (value == null) {
        } else if (value is bool) {
          Navigator.pop(context, true);
        } else if (value is FinalProcessReturn) {
          FinalProcessReturn finalProcessReturn = value;
          if (finalProcessReturn == null ) {
            Navigator.pop(context, finalProcessReturn);
          }
          if (finalProcessReturn.lpns == null || finalProcessReturn.lpns.length == 0) {
            Navigator.pop(context, finalProcessReturn);
          }
          setState(() {
            textEditingController.text = "";
            hint = "";
            data = finalProcessReturn.lpns;
          });
        }
      }).catchError((error) {
        // 错误处理
        print("An error occurred: $error");
      });

    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan original return lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    returnCheckTrackingCode(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }

}
